package org.third.common.utils.rest;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.third.common.utils.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * One RequestInterceptor is used to update the http header for rest api call
 *
 */
public class HttpHeaderHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    private Map<String, String> headers;

    public HttpHeaderHttpRequestInterceptor(Map<String, String> headers) {
        this.headers = headers == null ? new HashMap<String, String>() : headers;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        final HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
        headers.forEach((k, v) -> {
            if (StringUtils.hasText(k)) {
                requestWrapper.getHeaders().add(k, v);
            }
        });
        return execution.execute(requestWrapper, body);
    }
}
